package com.example.origin.finance.service;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

public abstract class AbstractCodeService extends AbstractUtilService {

    private static final int expire = 30;
    @Resource(name = "defaultRedisTemplate")
    private RedisTemplate<String, Set<String>> stringSetRedisTemplate;

    public List<String> listCode(String codeOption) {
        Set<String> list = new HashSet<>();
        if (ObjectUtil.isNotEmpty(codeOption)) {
            list.add(codeOption);
        } else {
            list = codes(codekey(), this::codeConsumer);
        }
        return new ArrayList<>(list);
    }

    protected abstract String codekey();

    protected abstract void codeConsumer(Set<String> sets);

    private Set<String> codes(String setkey, Consumer<Set<String>> consumer) {
        Set<String> stringSet = stringSetRedisTemplate.opsForValue().get(setkey);
        if (ObjectUtil.isEmpty(stringSet)) {
            stringSet = new HashSet<>();
            consumer.accept(stringSet);
            stringSetRedisTemplate.opsForValue().set(setkey, stringSet, expire, TimeUnit.DAYS);
        }

        return stringSet;
    }
}
